<template>
  <div>
    <h3>添加用户</h3>
    <form>
      <div class="form-row">
        <div class="form-group col-md-4">
          <label for="name">姓名</label>
          <input type="text" v-model="user.name" class="form-control" id="name" placeholder="name">
        </div>
        <div class="form-group col-md-4">
          <label for="age">年龄</label>
          <input type="number" v-model="user.age" class="form-control" id="age" placeholder="age">
        </div>
        <div class="form-group col-md-4">
          <label for="gender">性别</label>
          <select id="gender" class="form-control" v-model="user.gender">
            <option selected>男</option>
            <option>女</option>
          </select>
        </div>
      </div>
      <input type="button" @click="saveUserInfo()" class="btn btn-primary" value="保存"/>
      <a href="#/user" class="btn btn-danger">取消</a>
    </form>
  </div>
</template>

<script>
  export default {
    name: "UserAdd",
    data() {
      return ({
        user: {},//定义user对象时要写成对象形式，不能直接写一个光秃秃的user
        msg: ''
      });
    },
    methods: {
      saveUserInfo() {
        this.$http.post(this.$api + "/user/add", this.user
        //     {
        //   name: this.user.name,
        //   age: this.user.age,
        //   gender: this.user.gender
        // }
        ).then((response) => {//这里必须使用箭头函数，否则this将为undefined
          //success是在后端定义的响应数据的key，其值为true/false
          this.msg = response.data.msg
          if (response.data.success) {
            this.$router.push("/user");//切换路由，用于隐藏添加页面，此处需要做监听
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>